local publish = {}
package.path = package.path ..';../?.lua'
local tool = require('lib/tool')
local Msg = tool.class('msg')
local msgType = {
    Normal = 1;
    UI = 2;
    Skill = 3;


}
function Msg:Ctor(sendTime, mType, tbParam)
    self.sendTime = os.time() + sendTime
    self.msgType = mType
    self.tbParam = tbParam

    self.smallestDlay = 0.2
    -- self.__lt = function(a,b)
    --     if a.sendTime < b.sendTime then
    --         return true
    --     else
    --         return false
    --     end
    -- end

    -- self.__eq = function(a,b)
    --     if a.msgType == b.msgType and
    --         math.abs(a.sendTime - b.sendTime) < Msg.smallestDlay then
    --         return true
    --     else
    --         return false
    --     end
    -- end
end

Msg.smallestDlay = 0.2
Msg.__lt = function(a,b)
    if a.sendTime < b.sendTime then
        return true
    else
        return false
    end
end

Msg.__eq = function(a, b)
    if a.msgType == b.msgType and
        math.abs(a.sendTime - b.sendTime) < Msg.smallestDlay then
        return true
    else
        return false
    end
end

local provider = tool.class('provider')

function provider:Ctor()
    self.msgQueue = tool.rankQueue:New()
    self.subscribers = {}
end

function provider:notify(msg)
    self.msgQueue:insert(msg)
end

function provider:subscribe(aSubscriber,aMsgType)
    if self.subscribers[aMsgType] == nil then
        self.subscribers[aMsgType] = {}
    end
    table.insert(self.subscribers[aMsgType], aSubscriber)
end

function provider:unSubscirbe(aSubscriber, aMsgType)
    if self.subscribers[aMsgType] == nil then
        return
    end
    table.remove(self.subscribers, aSubscriber)
end

function provider:update(curTime, interval)
    local msg = self.msgQueue:last()
    if not msg then
        return
    end

    if curTime > msg.sendTime then
        self.msgQueue:pop()
        self:sendMsg(msg)
    end
end

function provider:sendMsg(msg)
    if self.subscribers[msg.msgType] then
        for _,aSubscriber in pairs(self.subscribers[msg.msgType]) do
            aSubscriber:getMsg(msg)
        end
    end
end


local publisher = tool.class('publisher')

function publisher:Ctor()
end

function publisher:addMsgCenter(msgCenter)
    self.msgCenter = msgCenter
end

function publisher:publish(msg)
    self.msgCenter:notify(msg)
end


local subscriber = tool.class('subscribe')

function subscriber:Ctor(name, aProvider)
    self.name = name
    self.provider = aProvider
end

function subscriber:subscribe(msgType)
    self.provider:subscribe(self, msgType)
end

function subscriber:getMsg(msg)
    print(debug.traceback("this function need to relize for object"))
end


publish.provider = provider
publish.Msg = Msg
publish.msgType = msgType
publish.publisher = publisher
publish.subscriber = subscriber
return publish
